package com.lahuan.config.datasouce;

import com.mysql.cj.jdbc.MysqlDataSource;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

@Import({CustomDatasource2Properties.class, CustomDatasource1Properties.class})
@Configuration
public class CustomDatasourceConfig {

    @Autowired
    CustomDatasource1Properties props1;
    @Autowired
    CustomDatasource2Properties props2;


    @Bean("jdbcTemplate1")
    public JdbcTemplate jdbcTemplate1() throws SQLException {
        System.out.println("注册bean jdbcTemplate1");
        return new JdbcTemplate(ds1());
    }

    @Bean("jdbcTemplate2")
    public JdbcTemplate jdbcTemplate2( ) throws SQLException {
        System.out.println("注册bean jdbcTemplate2");
        return new JdbcTemplate(ds2());
    }

    @Primary
    @Bean("ds1")
    public DataSource ds1() throws SQLException {
        MysqlXADataSource ds = new MysqlXADataSource();
        ds.setPinGlobalTxToPhysicalConnection(true);
        ds.setUrl(props1.getUrl());
        DataSource proxy = XaProxyUtil.proxyDatasource(ds,props1.getUsername(),props1.getPassword(),"ds1");
        return proxy;
    }

    @Bean("ds2")
    public DataSource ds2() throws SQLException {
        MysqlXADataSource ds = new MysqlXADataSource();
        ds.setPinGlobalTxToPhysicalConnection(true);
        ds.setUrl(props2.getUrl());
        DataSource proxy = XaProxyUtil.proxyDatasource(ds, props2.getUsername(), props2.getPassword(),"ds2");
        return proxy;
    }


}
